import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

/*<与原生交互信号通道 >*/
const methodChannel = const MethodChannel('flutter_native_ios');

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  Future<dynamic> runIosMethod() async {
    const channel = const MethodChannel("message_channel_test");
    var result;
    try {
      result = await channel.invokeMethod("commeon");
      print("收到IOS计算结果：${result}");
      return Future.value(result);
    } on PlatformException catch (e) {
      return Future.error(e.toString());
    }
  }

  static const BasicMessageChannel<dynamic> runTimer = const BasicMessageChannel("run_time", StandardMessageCodec());

  static void initMessageHandler() {
    print("initMessageHandler");
    runTimer.setMessageHandler((dynamic value) {
      // 接收到的时间
      int time = value;
      print("value = $time");
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              new ListTile(
                title: new Text('FlutterMethodChannel与原生,(present)'),
                trailing: FlatButton(
                    onPressed: runIosMethod, child: Text("发送")),
              ),
              new ListTile(
                title: new Text('FlutterBasicMessageChannel与原生,(present)'),
                trailing: FlatButton(
                    onPressed: initMessageHandler, child: Text("接收")),
              ),
            ],
          ),
        ));
  }
}
